<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        style="float:left;"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownloadExcel"
      >
        下载车位信息模板
      </el-button>
      <div>
        <el-upload
          ref="upload"
          multiple
          action="string"
          :before-upload="onBeforeUploadImage"
          :http-request="UploadImage"
        >
          <el-button icon="el-icon-upload" type="primary" style="margin-left:10px;">导入车位信息</el-button>
          <div
            slot="tip"
            class="el-upload__tip"
          >只能上传excel文件</div>
        </el-upload>
      </div>
    </div>
    <el-row :gutter="20">
      <el-col
        v-for="item in parkingList"
        :key="item.pid"
        :span="3"
      >
        <div
          class="box"
          pointer
          @click="handleUpdate(item)"
        >
          <el-card
            :class="item.status == 0 ? 'box-card2': 'box-card'"
            shadow="hover"
          >
            <div
              slot="header"
              class="clearfix"
            >
              <span>{{ item.pid }}</span>
            </div>
            <div class="text item">
              {{ item.type == 0 ? '临时车位': item.type == 1 ? '车位待出售': '车位可出租' }}
            </div>
            <div class="text item">
              {{ item.uid == -1 ? '' : item.uid }}
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      title="修改车位信息"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item
          label="车位号"
          prop="pid"
        >
          <el-input
            v-model="temp.pid"
            disabled
          />
        </el-form-item>
        <el-form-item label="车位类型">
          <el-select
            v-model="temp.type"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="temp.status"
            class="filter-item"
            placeholder="Please select"
            value-key
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="车主"
          prop="uid"
        >
          <el-input v-model="temp.uid" />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parkingList, updateParking, uploadFiles } from '@/api/parking'
import { getToken } from '@/utils/auth'
import axios from 'axios'
const download = axios.create({
  baseURL: 'http://120.76.172.71/api/management/parkingSpaceTemplate',
  headers: { 'Authorization': getToken() },
  methods: 'get',
  responseType: 'blob'
})

// const uploadFiles = axios.create({
//   baseURL: 'http://120.76.172.71/api/management/perImportParkingSpace',
//   methods: 'post',
//   headers: { 'Authorization': getToken(), 'Content-Type': 'multipart/form-data' }
// })
export default {
  inject: ['reload'],
  data() {
    return {
      typeOptions: [{ label: '临时车位', key: '0' }, { label: '待出售车位', key: '1' }, { label: '可出租车位', key: '2' }],
      statusOptions: [{ label: '未停车', key: '0' }, { label: '已停车', key: '1' }],
      list: null,
      temp: { pid: '', type: null, status: null, uid: '' },
      parkingList: [],
      multipleSelection: [],
      dialogFormVisible: false,
      dialogStatus: '',
      dialogPvVisible: false,
      total: null
    }
  },
  mounted() { // mounted钩子函数（生命周期函数）相当window.onload函数，随页面一加载执行
    // 单一网络请求在student.js经过封装统一处理，这里需要导入这个文件
    parkingList().then(res => {
      console.log('parkingList :', res)
      this.parkingList = res.data.parkingSpaces
      console.log(res.data)
    }, err => {
      console.log('err :', err)
    })
  },
  methods: {
    handleDownloadExcel() {
      download().then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', this.$route.meta.title + '.xls')
        document.body.appendChild(link)
        console.log(res)
        link.click()
      })
    },
    // 文件提交之前的操作 可以进行type类型的判断
    onBeforeUploadImage(file) {
      console.log(file)
    },
    // 文件提交
    UploadImage(param) {
      const fd = new FormData()
      console.log('param.file', param.file)
      fd.append('file', param.file) // 要提交给后台的文件
      uploadFiles(fd).then(res => { // UploadFiles 是封装的接口
        if (res.code !== 101) {
          this.$notify({
            title: 'Error',
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        } else {
          this.$notify({
            title: 'Success',
            message: '上传成功，' + res.msg,
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) { // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateParking(this.temp).then((res) => {
            if (res.code === 101) {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.reload()
            } else {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Error',
                message: '更新失败',
                type: 'error'
              })
            }
          })
        }
      })
    }
  }

}
</script>

<style>
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.text {
  font-size: 12px;
  color: #333;
  text-align: center;
}
.clearfix {
  text-align: center;
  font-size: 20px;
  color: #111;
}
.box {
  height: 200px;
}
.box-card {
  margin-top: 20px;
  background: #ccc;
  height: 200px;
}
.box-card2 {
  margin-top: 20px;
  background: #3c8;
  height: 200px;
}
</style>
